import { message } from 'antd';
import { updateUser, getUserInfo, checkUser, queryUserList} from '../services/api';

export default {
  namespace: 'userManage',

  state: {
    data: {
      list: [],
      pagination: {},
    },
    userInfo: {},
    userList: [],
    loading: true,
  },

  effects: {
    *fetch({ payload }, { call, put }) {
      const response = yield call(queryUserList, payload);
      yield put({
        type: 'userList',
        payload: response,
      });
    },
    *add({ payload, callback }, { call, put }) {
      yield put({
        type: 'changeLoading',
        payload: true,
      });
      const response = yield call(updateUser, payload);
      yield put({
        type: 'save',
        payload: response,
      });
      yield put({
        type: 'changeLoading',
        payload: false,
      });

      if (callback) callback();
    },
    *update({ payload, callback }, { call, put }) {
      const response = yield call(updateUser, payload);
      yield put({
        type: 'save',
        payload: response,
      });
    },
    *updateStatus({ payload, callback }, { call, put }) {
      const response = yield call(checkUser, payload);
      console.log('response', response.code);
      if (response.code === 0) {
        message.success('审核成功');
        if (callback) callback();
      }
    },
    *info({ payload }, { call, put }) {
      const response = yield call(getUserInfo, payload);
      yield put({
        type: 'userDetails',
        payload: response,
      });
    },
  },

  reducers: {
    save(state, action) {
      return {
        ...state,
        data: action.payload,
      };
    },
    userDetails(state, action) {
      return {
        ...state,
        userInfo: action.payload.data,
      };
    },
    changeLoading(state, action) {
      return {
        ...state,
        loading: action.payload,
      };
    },
    userList(state, action) {
      return {
        ...state,
        userList: action.payload.data,
      };
    },
  },
};
